<!-- 新建实物奖品 -->
<template>
  <a-drawer v-model:visible="vdata.visible" :maskClosable="false" width="40%" @close="onClose">
    <template #title>
      <div style="display:flex;justify-content:space-between;align-items:center;">
        <span>商户信息</span>
      </div>
    </template>
    <div class="content">
      <div class="top">
        <div class="header">
          <div class="img" />
          <div class="title">商户收单基础信息</div>
        </div>
        <div class="contentList" style="margin-top: 20px;padding:0 15px 15px 15px;box-sizing: border-box;">
          <a-row justify="space-between" type="flex">
            <a-col :sm="8">
              <a-descriptions>
                <a-descriptions-item label="商户号">
                  {{ vdata.saveObject['mchNo'] ? vdata.saveObject['mchNo'] : '--' }}
                </a-descriptions-item>
              </a-descriptions>
            </a-col>
            <a-col :sm="8">
              <a-descriptions>
                <a-descriptions-item label="商户手机号">
                  {{ vdata.saveObject['phone'] ? vdata.saveObject['phone'] : '--' }}
                </a-descriptions-item>
              </a-descriptions>
            </a-col>
            <a-col :sm="8">
              <a-descriptions>
                <a-descriptions-item label="商户地址">
                  {{ vdata.saveObject['address'] ? vdata.saveObject['address'] : '--' }}
                </a-descriptions-item>
              </a-descriptions>
            </a-col>
            <a-col :sm="8">
              <a-descriptions>
                <a-descriptions-item label="商户名称">
                  {{ vdata.saveObject['mchName'] ? vdata.saveObject['mchName'] : '--' }}
                </a-descriptions-item>
              </a-descriptions>
            </a-col>
            <a-col :sm="8">
              <a-descriptions>
                <a-descriptions-item label="商户简称">
                  {{ vdata.saveObject['mchShortName'] ? vdata.saveObject['mchShortName'] : '--' }}
                </a-descriptions-item>
              </a-descriptions>
            </a-col>
            <a-col :sm="8">
              <a-descriptions>
                <a-descriptions-item label="商户归属">
                  {{ vdata.saveObject['orgName'] ? vdata.saveObject['orgName'] : '--' }}
                </a-descriptions-item>
              </a-descriptions>
            </a-col>
          </a-row>
        </div>
      </div>
      <div class="bottom">
        <div class="header">
          <div class="img" />
          <div class="title">商户营销基础信息</div>
        </div>
        <div class="contentList" style="margin-top: 20px;padding:0 15px 15px 15px;box-sizing: border-box;">
          <a-form
            ref="formRef"
            :model="vdata.saveObject"
            layout="vertical"
            labelAlign="left"
            :rules="vdata.rules"
            :colon="false"
            :wrapper-col="{ span: 22 }"
            style="margin-top: 30px; margin-left: 20px; padding-bottom: 30px"
          >
            <a-row>
              <a-col :span="8">
                <a-form-item label="商户营销端名称" name="mchShortName">
                  <a-input v-model:value="vdata.saveObject['mchShortName']" placeholder="请输入商户营销端名称" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="商户经纬度" name="location">
                  <!-- <a-input v-model:value="vdata.saveObject['location']" :disabled="!vdata.isAdd" /> -->
                  <span>({{ vdata.saveObject.location?.longitude }}   {{ vdata.saveObject.location?.latitude }})</span>
                  <!-- <span>{{ isLoacation }}</span> -->
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="是否为优质商户" name="orderSort">
                  <a-switch :checked="vdata.saveObject.orderSort === 1" checked-children="是" un-checked-children="否" @change="(checked) => vdata.saveObject.orderSort = checked ? 1 : 0" />
                </a-form-item>
              </a-col>
            </a-row>
            <div class="line" style="width: 100%;height: 0px;border: 1px solid #EEEEEE;margin-bottom: 20px;" />
            <a-row>
              <a-col :span="12">
                <a-form-item label="商户展示头图:（16：9）" name="mchBannerImage">
                  <GzUpload v-model:src="vdata.saveObject['mchBannerImage']" bizType="activity" />
                </a-form-item>
              </a-col>

              <a-col :span="12">
                <a-form-item label="商户缩略图:（1：1）" name="mchListImage">
                  <GzUpload v-model:src="vdata.saveObject['mchListImage']" bizType="activity" />
                </a-form-item>
              </a-col>
            </a-row>
            <div class="line" style="width: 100%;height: 0px;border: 1px solid #EEEEEE;margin-bottom: 20px;" />
            <!-- 引入地图组件  -->
            <GzAmap ref="gzAmapRef" />
          </a-form>
        </div>
        <div class="contentList" style="margin-top: 20px;padding:0 15px 15px 15px;box-sizing: border-box;" />
      </div>
    </div>
    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" style="margin-right: 8px" @click="onClose">
        <close-outlined />
        取消
      </a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="handleOkFunc">
        <check-outlined />
        保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import {$apiAgentAppAdd,$apiAgentAppUpdate,$apiAgentAppDetail} from '@/api/proxy/programManage/lite/index'
import {$getUploadFormParams } from '@/api/manage'
import{$getMchList,$apiMchInfoUpdateProcessMch}from  '@/api/mch/index'
import { reactive, ref, defineExpose, getCurrentInstance,computed,nextTick } from 'vue'
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties
const formRef = ref()
const gzThreeRef = ref()
const gzAmapRef = ref()

const props = defineProps(['callbackFunc'])
// 计算属性处理开关状态
const isOrderSortEnabled = computed({
  get() {
    return vdata.saveObject.orderSort === 1
  },
  set(newValue) {
    vdata.saveObject.orderSort = newValue ? 1 : 0
  }
})
// 计算属性：双向绑定
const changeOrderSort = (checked) =>{
  console.log('开关状态变化:', checked)
  if(!checked){
    vdata.saveObject.orderSort =0
  }else{
    vdata.saveObject.orderSort =1
  }
}
const vdata:any = reactive({
  isAdd: false, // 新增OR修改
  visible: false,
  btnLoading: true,
  saveObject: {
    
  },
  rules: {
    appId: [{ required: true, message: 'appid不能为空', trigger: 'blur' },],
    appSecret: [{ required: true, message: 'appsecret不能为空', trigger: 'blur' },],
    name: [{ required: true, message: '小程序名称不能为空', trigger: 'blur' },],
    authUrl: [{ required: true, message: '公众号获取open_id配置的url不能为空', trigger: 'blur' },],
    imgUrl: [{ required: true, message: '公众号二维码不能为空', trigger: 'blur' },],
    scoreRule: [{ required: true, message: '请上传福分规则图片', trigger: 'blur' },],
    agentNo: [{ required: true, message: '机构不能为空', trigger: 'blur' },],
    privacyPolicy: [{ required: true, message: '隐私政策不能为空', trigger: 'blur' },],
    serviceAgreement: [{ required: true, message: '服务协议不能为空', trigger: 'blur' },],
    remark: [{ required: true, message: '备注不能为空', trigger: 'blur' },],
  },
})

function handleOkFunc() {
  formRef.value.validate().then(()=>{
    // vdata.btnLoading = true
    let message = vdata.isAdd ? '新增成功' : '修改成功'
    if(vdata.isAdd){
    }else{
      // 编辑
      let mapData = gzAmapRef.value.getMapData()
      if (!mapData || mapData.areacode.length == 0 || !mapData.address || !mapData.lnglat) {
          return $infoBox.message.error('请选择地理位置')
        }
        if (mapData.lnglat.indexOf(',') < 0) {
          return $infoBox.message.error('请输入正确的经纬度')
        }
      console.log(mapData,'mapData')
      vdata.saveObject.location ={
          longitude:mapData.lnglat.split(',')[0],
          latitude:mapData.lnglat.split(',')[1]
        }
        vdata.saveObject.address = mapData.address
        vdata.saveObject.areaCode = JSON.stringify(mapData.areacode)
        vdata.saveObject.areaName = JSON.stringify(mapData.areacodeNames)
      $apiMchInfoUpdateProcessMch(vdata.saveObject).then(res=>{
        $infoBox.message.success(message)
        props.callbackFunc()
        vdata.visible = false
      }).finally(()=>{
        vdata.btnLoading = false
      }).catch(()=>{})
    }
})
}

function parseOrEmpty(jsonStr) {
    try {
        const parsed = JSON.parse(jsonStr)
        // 可选：进一步检查是否是数组（如必须是 `["xxx"]` 格式）
        if (Array.isArray(parsed)) {
            return parsed
        }
        return '' // 如果不是数组，也返回空字符串
    } catch (error) {
        return '' // 解析失败返回空字符串
    }
}

function show(record) {
  vdata.isAdd = !record
  // 重置数据
  vdata.btnLoading = false
  vdata.saveObject = {}
  let initMapData : any = {}
    // 修改
    $getMchList({ mchNo: record.mchNo }).then(res=>{
      // 商圈的位置信息包含了区域编码
      if(res.records[0].areaCode && res.records[0].areaCode.length){
                  initMapData.areacode = JSON.parse(res.records[0].areaCode)
                  initMapData.lnglat = res.records[0].location?.longitude + ',' + res.records[0].location.latitude
                  initMapData.address = res.records[0].address
                  // initMapData.areacodeNames = JSON.parse(res.records[0].areaName)
                  initMapData.areacodeNames = parseOrEmpty(res.records[0].areaName)
                }
                // setTimeout(()=>{
                //   gzAmapRef.value.init(initMapData)
                // })
                Object.assign(vdata.saveObject, {
                  ...res.records[0],
                })
                vdata.visible = true
                // 确保组件已挂载
                nextTick(()=>gzAmapRef.value.init(initMapData))
                //  setTimeout(()=>{
                //   gzAmapRef.value.init(initMapData)
                // })
                
    })
    
}
// 清除字段验证
// function clearFieldValidate(){
//   if (formRef.value !== undefined) {
//     formRef.value.clearValidate()
//   }
// }
const onClose = () => {
  vdata.visible = false
}
defineExpose({
  show,
})
</script>

<style lang="less" scoped>
  .content{
    width: 100%;
    height: 100%;
    .top{
      width: 100%;
      // height: 100%;
      .header{
        width: 100%;
        height: 40px;
        background: #FAFAFA;
        border-radius: 4px 4px 0px 0px;
        display: flex;
        align-items: center;
        .img{
          width: 2px;
          height: 14px;
          background: #0671EB;
          border-radius: 0px 0px 0px 0px;
          margin-left: 10px;
          margin-right: 8px;
          
        }
      }
    }

    .bottom{
      width: 100%;
      height: 250px;
      .header{
        width: 100%;
        height: 40px;
        background: #FAFAFA;
        border-radius: 4px 4px 0px 0px;
        display: flex;
        align-items: center;
        .img{
          width: 2px;
          height: 14px;
          background: #0671EB;
          border-radius: 0px 0px 0px 0px;
          margin-left: 10px;
          margin-right: 8px;
          
        }
      }
    }
  }
.rule{
  display: flex;
  align-items: center;
  gap: 20px;
  *{
    flex-shrink: 0;
  }
  &:nth-child(n + 2){
    margin-top: 10px;
  }
}
.cp{
  cursor: pointer;
}
.fz18{
  font-size: 18px;
}
</style>
